package com.bone.eventsweb.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bone.eventsweb.dao.UserDao;
import com.bone.eventsweb.entity.UserEntity;
import com.bone.eventsweb.exception.ServiceException;
import com.bone.eventsweb.service.UserService;
import com.bone.eventsweb.utils.Result;
import com.bone.eventsweb.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.server.ServerCloneException;


@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    UserDao userDao;

    /**
     * 登录逻辑
     * @param user
     * @return
     */
    @Override
    public UserEntity login(UserEntity user) {
        //根据用户名查询数据库的用户信息
        UserEntity dbUser = userDao.selectByUsername(user.getUsername());
        if (dbUser == null){
            //抛出一个自定义的异常信息
            throw  new ServiceException("用户名密码错误");
        }
        //先判断表单元素传来的密码是否为null  在去equals对比 数据库中的值否则 用null去equals 会报错
        if (!user.getPassword().equals(dbUser.getPassword())){
            throw  new ServiceException("用户名密码错误");
        }


        //生成token
        String token = TokenUtils.createToken(String.valueOf(dbUser.getId()), dbUser.getPassword());

        dbUser.setToken(token);

        return dbUser;
    }

    @Override
    public Result register(UserEntity user) {
        UserEntity dbUser = userDao.selectByUsername(user.getUsername());
        if (dbUser == null) {
            int num = userDao.insert(user);
            if (num > 0) {
                return Result.ok();
            } else {
                return Result.fail();
            }
        }else {
            return Result.fail();
        }
    }
}
